package com.weixing.mall.provider.auth.member.openid;

import com.weixing.mall.base.utils.EnumUtil;
import com.weixing.mall.provider.enums.MsgFlagEnum;
import com.weixing.oauth2.common.userdetails.IUserAuthService;
import com.weixing.oauth2.common.userdetails.SecurityUser;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author mall
 */
@Setter
public class MemberOpenIdAuthenticationProvider implements AuthenticationProvider {
    private IUserAuthService userDetailService;
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) {
        MemberOpenIdAuthenticationToken authenticationToken = (MemberOpenIdAuthenticationToken) authentication;
        // openid
        String openid = (String) authenticationToken.getPrincipal();
        SecurityUser user = userDetailService.loadUserByOpenId(openid);
        String msgFlag = user.getMsgFlag();
        if (!MsgFlagEnum.SUCCESS.getValue().equals(msgFlag)) {
            throw new InternalAuthenticationServiceException(EnumUtil.getDesp(MsgFlagEnum.class, msgFlag));
        }
        if (!user.isEnabled()){
            throw new DisabledException("该账户已禁用");
        }
        MemberOpenIdAuthenticationToken authenticationResult = new MemberOpenIdAuthenticationToken(user, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MemberOpenIdAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
